package com.datas.service.api;

import com.datas.beans.PageResourceApiItem;
import com.datas.db.hibernatebeans.UmsDepartment;
import com.datas.db.hibernatebeans.UmsRole;
import com.datas.db.hibernatebeans.UmsUser;
import com.datas.service.PermissionService;
import com.datas.utils.hbn.HbnTxRuner;
import org.hibernate.Session;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * Created by jige0727 on 2017/5/30.
 */
@Service
public class ApiUserService {
    @Autowired
    PermissionService permissionService;
    @Autowired
    ApiPermissionService apiPermissionService;

    public JSONObject userinfo(String access_token) {
        return (JSONObject) new HbnTxRuner() {
            @Override
            protected Object dataLogic() throws Exception {
                Integer userid = getUserIdByToken(access_token, getCurrentSession());
                if (userid == null) {
                    return null;
                }
                UmsUser user = getCurrentSession().get(UmsUser.class, userid);
                JSONObject res = new JSONObject();
                res.put("real_name", user.getReal_name());
                res.put("user_info", new JSONObject(user));

                List<UmsRole> roles = getUserRoleInfo(userid, getCurrentSession());
                res.put("roles", roles);

                List<PageResourceApiItem> resList = new ArrayList<>();
                resList.addAll(getUserPageResource_byRole(userid, getCurrentSession()));
                res.put("resources", resList);

                //获取工厂数据 在第三层
//                UmsDepartment factoryInfo = getUserFactoryInfo(userid, getCurrentSession());
//                res.put("factory", factoryInfo != null ? new JSONObject(factoryInfo) : null);
//                if (factoryInfo != null && factoryInfo.getParent_dept_id() != null) {
//                    res.put("parentDept", new JSONObject(getCurrentSession().get(UmsDepartment.class, factoryInfo.getParent_dept_id())));
//                }
                UmsDepartment factoryInfo = getUserFactoryInfo(userid, getCurrentSession());
                res.put("company", factoryInfo != null ? new JSONObject(factoryInfo) : null);
                List<UmsDepartment> manageFactoryInfo = getUserManageFactoryInfo(userid, getCurrentSession());
                res.put("manageCompanies", manageFactoryInfo != null ? manageFactoryInfo : null);
                return res;
            }
        }.run();
    }

    private Integer getUserIdByToken(String access_token, Session session) {
        return (Integer) session.createQuery("select i.users_id from UmsUserLoginToken i where i.access_token=:access_token")
                .setParameter("access_token", access_token).uniqueResult();
    }

    private List<UmsRole> getUserRoleInfo(Integer userid, Session session) {
        return session.createQuery("select r from UmsRole r " +
                "inner join UmsUser_UmsRole uu on r.id = uu.roles_id " +
                "where uu.users_id=:users_id ")
                .setParameter("users_id", userid).list();
    }

//    private List<PageResourceApiItem> getUserPageResource_byUser(Integer userid, Session session) {
//        return session.createQuery("select new com.datas.beans.PageResourceApiItem( " +
//                "r.rese_name, r.rese_uri, r.rese_type, r.sort_order, " +
//                "r.parent_rese_id, r.parent_rese_name, r.struct ) " +
//                "from UmsPageResource r " +
//                "inner join UmsUser_UmsPageResource ur on r.id = ur.pageresources_id " +
//                "where ur.users_id=:users_id ")
//                .setParameter("users_id", userid).list();
//    }

    public List<PageResourceApiItem> getUserPageResource_byRole(Integer userid, Session session) {
        List<Integer> roleids = permissionService.getUserCanseeRoleIds(userid, session);
        if (roleids.size() == 0) {
            roleids.add(-1);
        }
        return session.createQuery("select new com.datas.beans.PageResourceApiItem( " +
                "r.rese_name, r.rese_uri, r.rese_type, r.sort_order, " +
                "r.parent_rese_id, r.parent_rese_name, r.struct ) " +
                "from UmsPageResource r " +
                "inner join UmsRole_UmsPageResource rr on r.id = rr.pageresources_id " +
                "where rr.roles_id in (:roleids) ")
                .setParameterList("roleids", roleids).list();
    }

    private UmsDepartment getUserFactoryInfo(Integer userid, Session session) {
        return (UmsDepartment) session.createQuery("SELECT dept " +
                "FROM UmsDepartment dept " +
                "INNER JOIN UmsUser_UmsDepartment ud ON dept.id = ud.departments_id " +
                "WHERE dept.disabled =0 " +
                "AND ud.users_id = :users_id " +
                "AND dept.struct LIKE '%-%' " +
                "AND dept.struct NOT LIKE '%-%-%'")
                .setParameter("users_id", userid)
                .setMaxResults(1)
                .uniqueResult();
    }

    private List<UmsDepartment> getUserManageFactoryInfo(Integer userid, Session session) {
        return (List<UmsDepartment>) session.createQuery("SELECT dept " +
                "FROM UmsDepartment dept " +
                "INNER JOIN UmsUser_UmsDepartment_mng udm ON dept.id = udm.departments_id " +
                "WHERE dept.disabled =0 " +
                "AND udm.users_id = :users_id " +
                "AND dept.struct LIKE '%-%' " +
                "AND dept.struct NOT LIKE '%-%-%'")
                .setParameter("users_id", userid).list();
    }

    /**
     * 获取账号的类型 ums expert
     *
     * @param access_token
     * @return userType users_id
     */
    public Map<String, Object> getUserTypeBuToken(String access_token) {
        return (Map<String, Object>) new HbnTxRuner() {
            @Override
            protected Object dataLogic() throws Exception {
                return getUserTypeBuToken(access_token, getCurrentSession());
            }
        }.run();
    }

    public Map<String, Object> getUserTypeBuToken(String access_token, Session session) {
        return (Map<String, Object>) session.createQuery("select new map(i.userType as userType, i.users_id as users_id) " +
                "from UmsUserLoginToken i " +
                "where i.access_token=:access_token ")
                .setParameter("access_token", access_token)
                .uniqueResult();
    }

    /**
     * 获取专家的信息
     *
     * @param users_id
     * @return
     */
    public JSONObject userinfoExpert(Integer users_id) {
        JSONObject res = new JSONObject();
        UmsRole role = new UmsRole("专家", "03");

        List<UmsRole> roles = Arrays.asList(role);
        res.put("roles", roles);

        List<PageResourceApiItem> resList = apiPermissionService.getPageresourcesByRoleCode("03");
        res.put("resources", resList);
        return res;
    }
}
